import sqlite3
def check_schema(db, schema_file):
    schema_str = get_schema(db)
    file_str = open(schema_file).read()        
    if file_str.strip() != schema_str.strip():
        print "schema file changed, re-creating the database"
        drop_tables(db)
        create_tables(db, schema_file)
        schema_str = get_schema(db)        
    else: 
        print "no schema change"

def drop_tables(db):
    con = sqlite3.connect(db)        
    c = con.execute("select 'drop table ' || name || ';' from sqlite_master where type = 'table';")
    drop_commands = []        
    for row in c:
        drop_commands.append(row[0])
    for cmd in drop_commands:
        print cmd
        con.execute(cmd)
    con.commit()
def get_schema(db):
    con = sqlite3.connect(db)
    res = con.execute("select sql from sqlite_master where type='table' or type='index'")
    sqls = []
    for row in res:            
        sqls.append(str(row[0]))        
    return '\n'.join(sqls)
def create_tables(db, schema_file):
    con = sqlite3.connect(db)        
    for line in open(schema_file):            
        if not line:
            break
        if line[:-1] == '\n':
            line = line[:-1]        
        con.execute(line)
    con.commit()